<template>
  <div class="page-common-layout">
    <div class="page-common-left">
      <div class="header">
        <span class="title">{{
          $ct("mdataOrganizationIndex", "组织机构")
        }}</span>
        <span>
          <!-- <a-icon type="more" @click="openOrgView" /> -->
        </span>
      </div>
      <div class="padding-xs">
        <a-input-search
          placeholder="组织机构名称"
          style="width: 100%"
          @search="onSearch"
        />
      </div>
      <div class="body">
        <!-- <a-tree
					:tree-data="searchTree"
					:replaceFields="{children:'children', title:'orgName', key:'id' }"
					:defaultExpandAll="true"
					v-if="showMenu"
					@select="selectTree"
		    /> -->
        <ZTree
          ref="masterList"
          :columns="columns"
          rowKey="uuid"
          :url="url"
          :parameter="parameter"
          :masterMust="false"
          :formatConditions="false"
          :showSearch="false"
          :loadAll="true"
          :expandAll="false"
          treeText="orgName"
          :isFirst="true"
          @rowClick="
            (e) => {
              masterRowClick(e);
            }
          "
        >
        </ZTree>
      </div>
    </div>
    <div class="page-common-content">
      <tool-bar
        @search="$refs.subList.refresh(true)"
        @reset="
          () => {
            (subQueryParam = {}), $refs.subList.refresh(true);
          }
        "
      >
        <template slot="toolBtn" slot-scope="scope">
          <!-- -->
          <a-button
            class="cu-btn-primary"
            icon="plus"
            @click="handleAdd('1', $refs.masterList.data, 'sub')"
            v-action:addUserInfo
          >
            新建用户
          </a-button>
          <!-- 系统管理员专用新建 -->
          <!-- -->
          <!-- <a-button
            class="cu-btn-primary"
            icon="plus"
            @click="handleAdminAdd($refs.masterList.data)"
            v-action:adminAddUserInfo
          >
            新建用户
          </a-button> -->
          <a-button
            type="link"
            icon="delete"
            @click="recycleBin"
            v-action:userRecyclebin
            >回收站</a-button
          >
          <!-- <a-button
            class="cu-btn-primary"
            icon="eye"
            @click="changeStatus('UserInfoStatus.01', 'UserStatus')"
            v-action:openAccount
          >
            打开账号
          </a-button>
          <a-button
            class="cu-btn-primary"
            icon="eye-invisible"
            @click="changeStatus('UserInfoStatus.03', 'UserStatus')"
            v-action:closeAccount
          >
            关闭账号
          </a-button>
          <a-button
            class="cu-btn-primary"
            icon="user-delete"
            @click="changeStatus('UserLock.02', 'UserLock')"
            v-action:lockAccount
          >
            锁定账号
          </a-button>
          <a-button
            class="cu-btn-primary"
            icon="user-add"
            @click="changeStatus('UserLock.01', 'UserLock')"
            v-action:unlockAccount
          >
            解锁账号
          </a-button> -->
          <!-- <export-data
            fileName="用户信息"
            fieldInfoUrl="/mdata/user/getFieldInfo"
            exportUrl="/mdata/user/exportSysUserData"
          ></export-data> -->
          <a-icon
            type="setting"
            @click="columnSort"
            style="float: right; margin: 9px 5px 0 0;"
          />
          <!-- <a-button class="cu-btn-primary" icon="plus" @click="handleAdd('1', $refs.masterList.data, 'sub')">批量授权</a-button> -->
          <!-- <a-button icon="undo" @click="resetPassword()" type="link">{{$ct("resetPassword","重置密码")}}</a-button> -->
        </template>
        <template slot="toolForm">
          <a-form-item label="账号">
            <a-input v-model="subQueryParam.userNameId" placeholder="账号" />
          </a-form-item>
          <a-form-item :label="$ct('fullName', '姓名')">
            <a-input
              v-model="subQueryParam.userName"
              :placeholder="$ct('fullName', '姓名')"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <DataGrid
        v-if="showTable"
        ref="subList"
        type="sub"
        :url="url"
        :columns="subColumns"
        :showRowSelect="true"
        :queryParam="subQueryParam"
        rowKey="uuid"
        showPagination="auto"
        @rowClick="
          (e) => {
            subRowClick(e);
          }
        "
        @onSelectChange="
          (rowsKey, rows) => {
            subSelectChange(rowsKey, rows);
          }
        "
      >
        <span slot="renderUserSex" slot-scope="{ text }">
          {{ text | sexFilter }}
        </span>
        <span slot="renderUserHeadPortrait" slot-scope="{ text }">
          <img
            :src="text"
            alt=""
            class="business-license"
            @click="preViewHeadPortrait(text)"
          />
        </span>
        <span slot="renderUserStatus" slot-scope="{ text }">
          <a-tag :color="text === 'UserInfoStatus.01' ? 'green' : 'red'">
            {{ text | statusFilter }}
          </a-tag>
        </span>
        <span slot="renderUserLock" slot-scope="{ text }">
          <a-tag :color="text === 'UserLock.01' ? 'green' : 'red'">
            {{ text | lockFilter }}
          </a-tag>
        </span>
        <span slot="renderAction" slot-scope="{ text, record }">
          <template>
            <!-- <a
              @click="handleAdminEdit(record, $refs.masterList.data)"
              v-action:loginAccount
              >{{ $ct("loginAccount", "登陆账号") }}</a
            >
            <span class="action-margin"></span> -->
            <a
              @click="handleEdit(record, $refs.masterList.data, 'sub')"
              v-action:userEdit
              >{{ $ct("edit", "编辑") }}</a
            >
            <span class="action-margin"></span>
            <a
              @click="handleSub(record, 'sub')"
              :class="
                record.userNameId === 'ewsd0001'
                  ? 'a-disabled'
                  : 'action-delete'
              "
              v-action:userDelete
              >{{ $ct("delete", "删除") }}</a
            >
            <a-dropdown>
              <a class="ant-dropdown-link" v-action:userMore>
                {{ $ct("more", "更多") }}
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="openPwdModal(record)" v-action:changePassword
                    >修改密码</a
                  >
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </DataGrid>
      <editForm
        ref="subModal"
        :visible="subVisible"
        :loading="subConfirmLoading"
        :model="subMdl"
        @cancel="handleCancel('sub')"
        @ok="handleOk('sub')"
      />

      <adminEditForm
        ref="adminModal"
        :visible="adminVisible"
        :model="adminMdl"
        @cancel="handleAdminCancel"
        @ok="handleAdminOk"
      />

      <org-preview
        ref="viewOrgModal"
        :visible="viewOrgVisible"
        @cancel="viewOrgVisible = false"
      >
      </org-preview>

      <preview-image
        :visible.sync="visibleViewImg"
        :imgSrc="imgSrc"
      ></preview-image>

      <ColumnSort
        :visible="columnSortVisible"
        :columns="subColumns"
        @ok="columnSortConfirm"
        @cancel="columnSortCancel"
      >
      </ColumnSort>

      <pwd-modal
        :visible="pwdVisible"
        :userUuid="userUuid"
        :accountNumber="accountNumber"
        @confirm="updatePassword"
        @cancel="pwdVisible = false"
      >
      </pwd-modal>

      <recycle-bin
        :visible="recycleBinVisible"
        @refresh="$refs.subList.refresh()"
        @cancel="recycleBinVisible = false"
      >
      </recycle-bin>
    </div>
  </div>
</template>
<script>
import { TreeGrid, DataGrid, ZTree, ExportData } from "@/components";
import { treeGridMixin } from "@/mixins/treeGridMixin";
import editForm from "./edit.vue";
import adminEditForm from "./adminEdit.vue";
import orgPreview from "@/components/TopVUI/custom/orgPreview.vue";
import previewImage from "@/components/TopVUI/custom/previewImage.vue";
import pwdModal from "./pwdModal.vue";
import RecycleBin from "./RecycleBin.vue";
export default {
  mixins: [treeGridMixin],
  components: {
    adminEditForm,
    editForm,
    TreeGrid,
    DataGrid,
    orgPreview,
    previewImage,
    ExportData,
    pwdModal,
    RecycleBin,
    ZTree,
  },
  data() {
    return {
      showTable: false,
      key: "1",
      columns: [
        {
          title: "组织机构",
          align: "left",
          dataIndex: "text",
          langCode: "mdataOrganizationIndex",
        },
      ],
      subColumns: [
        {
          title: "用户账号",
          align: "center",
          dataIndex: "userNameId",
          width: 150,
        },
        {
          title: "用户姓名",
          dataIndex: "userName",
          width: 150,
        },
        {
          title: "手机号码",
          dataIndex: "userCellphone",
          width: 150,
        },
        {
          title: "单位",
          dataIndex: "affiliatedUnitName",
          width: 150,
        },
        {
          title: "部门",
          dataIndex: "orgName",
          langCode: "null",
          width: 150,
        },
        {
          title: "账号状态",
          align: "center",
          dataIndex: "userStatus",
          scopedSlots: {
            customRender: "renderUserStatus",
          },
          width: 80,
        },
        {
          title: "锁定状态",
          align: "center",
          dataIndex: "userLock",
          scopedSlots: {
            customRender: "renderUserLock",
          },
          width: 80,
        },
        // {
        //   title: "创建时间",
        //   dataIndex: "createTime",
        //   width: 150,
        // },
        {
          title: "操作",
          align: "center",
          dataIndex: "action",
          width: 150,
          scopedSlots: {
            customRender: "renderAction",
          },
          fixed: "right",
        },
      ],
      masterVisible: false,
      subVisible: false,
      masterConfirmLoading: false,
      subConfirmLoading: false,
      masterMdl: null,
      subMdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      subQueryParam: {},
      url: {
        fathersUrl: "/mdata/organization/getTreeSysOrganization",
        // fathersUrl: "/mdata/organization/getListByPid",// 企业微信导入组织机构没有层级不能用上面的
        expandUrl: "/mdata/organization/getListByPid",
        subList: "/mdata/user/getPageSet",
        subSave: "/mdata/user/save",
        subUpdate: "/mdata/user/update",
        subDelete: "/mdata/user/delete",
        getUserPost: "/mdata/sysUserPost/getPageSet",
        savePosition: "/mdata/user/savePosition",
        updatePosition: "/mdata/sysUserPost/update",
        delUserPost: "/mdata/sysUserPost/deleteBatch",
      },
      parameter: {
        father: {
          levelId: 1,
          pid: 1,
        },
        children: {},
      },
      postQueryParam: {},
      searchTree: [],
      showMenu: false,
      viewOrgVisible: false,
      visibleViewImg: false,
      imgSrc: "",
      columnSortVisible: false,
      pwdVisible: false,
      userUuid: "",
      accountNumber: "",
      recycleBinVisible: false,
      selectUuid: [],
      adminVisible: false,
      adminConfirmLoading: false,
      adminMdl: null,
    };
  },
  activated() {},
  filters: {
    sexFilter(sex) {
      const sexMap = {
        "UserSex.01": "男",
        "UserSex.02": "女",
        "UserSex.03": "未知",
      };
      return sexMap[sex];
    },
    statusFilter(status) {
      const statusMap = {
        "UserInfoStatus.01": "正常",
        "UserInfoStatus.02": "锁定",
        "UserInfoStatus.03": "禁用",
        "UserInfoStatus.04": "离职",
        "UserInfoStatus.05": "注销",
        "UserInfoStatus.06": "删除",
      };
      return statusMap[status];
    },
    lockFilter(lock) {
      const lockMap = {
        "UserLock.01": "正常",
        "UserLock.02": "锁定",
      };
      return lockMap[lock];
    },
  },
  methods: {
    getOrgTree() {
      this.$post("/mdata/organization/getTreeSysOrganization").then((res) => {
        this.treeData = JSON.parse(JSON.stringify(res));
        this.searchTree = JSON.parse(JSON.stringify(res));
        this.showMenu = true;
      });
    },
    masterRowClick(record) {
      this.$refs.masterList.rows = record;
      this.subQueryParam.orgId = record.id;
      this.postQueryParam = {};
      this.showTable && this.$refs.subList.refresh();
      this.showTable = true;
    },
    subRowClick(record) {
      this.postQueryParam.orgId = record.orgId;
      this.postQueryParam.userNameId = record.userNameId;
    },
    // 重置密码
    resetPassword() {
      if (this.$refs.subList.selectedRows.length === 0) {
        this.$message.warn("请先勾选需要操作的用户");
      } else {
        let uuid = [],
          password = [];
        this.$refs.subList.selectedRows.forEach((req, index) => {
          uuid.push(req.uuid);
          password.push(req.userNameId);
        });
        this.$post("/mdata/user/updatePassword", {
          uuid: uuid.toString(),
          password: password.toString(),
        }).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success(res.message);
            this.$refs.subList.refresh();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    //菜单搜索
    onSearch(value) {
      this.$refs.masterList.data = this.treeFilter(
        value,
        JSON.parse(JSON.stringify(this.$refs.masterList.originalData))
      );
    },
    selectTree(value, node, extra) {
      this.subQueryParam.orgId = value[0];
      this.$refs.subList.refresh(true);
    },
    //树形数据过滤
    treeFilter(value, arr) {
      if (!arr) {
        return [];
      }
      let newarr = [];
      arr.forEach((item) => {
        if (item.orgName.indexOf(value) > -1) {
          let redata = this.treeFilter(value, item.children);
          let obj = {
            ...item,
            children: redata,
          };
          newarr.push(obj);
        } else {
          if (item.children && item.children.length > 0) {
            let redata = this.treeFilter(value, item.children);
            let obj = {
              ...item,
              children: redata,
            };
            if (redata && redata.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    },
    openOrgView() {
      this.viewOrgVisible = true;
      this.$refs.viewOrgModal.getOrgData(this.$refs.masterList.data);
    },
    preViewHeadPortrait(val) {
      this.imgSrc = val;
      this.visibleViewImg = true;
    },
    columnSort() {
      this.columnSortVisible = true;
    },
    columnSortConfirm() {
      this.columnSortVisible = false;
    },
    columnSortCancel() {
      this.columnSortVisible = false;
    },
    openPwdModal(e) {
      this.userUuid = e.uuid;
      this.accountNumber = e.userNameId;
      this.pwdVisible = true;
    },
    updatePassword() {
      this.pwdVisible = false;
    },
    recycleBin() {
      this.recycleBinVisible = true;
    },
    subSelectChange(rowsKey, rows) {
      this.selectUuid = rowsKey;
    },
    changeStatus(data, type) {
      if (this.selectUuid.length === 0)
        return this.$message.error("请先勾选需要操作的用户!");
      const params = {
        uuid: this.selectUuid.toString(),
        userStatus: data,
        type: type,
      };
      this.$post("/mdata/user/updateSysUserStatus", params).then((res) => {
        if (res.statusCode === 200) {
          this.$message.success("改变状态成功");
          this.$refs.subList.refresh();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    handleAdminAdd(data) {
      let form = this.$refs.adminModal.form;
      form.resetFields();
      this.adminVisible = true;
      this.$refs.adminModal.title = "新建";
      this.adminMdl = this.subQueryParam;
      if (this.$refs.adminModal.add)
        this.$refs.adminModal.add(this.adminMdl, data);
    },
    handleAdminEdit(record, data) {
      this.adminVisible = true;
      this.adminMdl = record;
      if (this.$refs.adminModal.edit)
        this.$refs.adminModal.edit(this.adminMdl, data);
    },
    handleAdminOk() {
      let form = this.$refs.adminModal.form;
      form.validateFields((errors, values) => {
        if (!errors) {
          if (typeof values.uuid === "undefined") {
            this.$post("/mdata/user/save", values).then((res) => {
              if (res.statusCode === 200) {
                this.$message.success(
                  res.message ? res.message : "新建用户成功"
                );
                this.$refs.subList.refresh();
              } else {
                this.$message.error(res.message);
              }
            });
          } else {
            this.$post("/mdata/user/update", values).then((res) => {
              if (res.statusCode === 200) {
                this.$message.success(
                  res.message ? res.message : "更新用户成功"
                );
                this.$refs.subList.refresh();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        }
      });
      this.adminVisible = false;
      this.adminMdl = {};
    },
    handleAdminCancel() {
      this.adminVisible = false;
      this.adminMdl = {};
    },
    handleDownload() {},
  },
};
</script>

<style scope lang="less">
.business-license {
  cursor: pointer;
  padding: 5px;
  height: 36px !important;
  width: 36px !important;
}
.page-common-left {
  display: flex;
  width: 300px;
  flex-shrink: 0;
  flex-direction: column;
  padding: 0;

  .header {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    color: #606266;
    padding: 10px;
    height: 50px;
    box-sizing: border-box;

    .title {
      font-size: 16px;
    }
  }

  .body {
    padding: 10px;
    overflow: auto;
    flex: 1;
  }
}
</style>
